#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Comm.hpp"

#define CONV(addr) ((struct sockaddr *)addr) // 定义宏便于使用
#define Retry_Count 5

using namespace std;

void Usage(std::string proc) // 提示说明
{
    cout << "Usage: \n\t" << proc << " local_port\n"
         << endl;
}

bool visitServer(string &serverip, uint16_t &serverport, int *cnt)
{
    // 1. 创建socket
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        cerr << "socket error" << endl;
        return false;
    }

    bool ret = true;
    string inbuffer;
    char service_list[1024];
    ssize_t m;
    // 2. 要不要bind？必须要有Ip和Port，需要bind，但是不需要用户显示bind
    // 发起连接的时候，client会被OS自动进行本地绑定
    // 2. 建立连接
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    // p:process(进程)，n（网络）——不太准确但好记忆
    inet_pton(AF_INET, serverip.c_str(), &server.sin_addr); // 1.字符串ip->4字节ip 2.->网络序列  更现代更安全
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    int n = connect(sockfd, CONV(&server), sizeof(server)); // 自动bind
    if (n < 0)
    {
        cerr << "connect error" << endl;
        ret = false;
        goto END;
    }
    m = write(sockfd, service_list, sizeof(service_list) - 1);
    if (m > 0)
    {
        service_list[m] = 0;
        cout << "服务器提供的服务列表是：" << service_list << endl;
    }
    *cnt = 1;

    cout << "Please Select Service# ";
    getline(cin, inbuffer);
    write(sockfd, inbuffer.c_str(), inbuffer.size());

    while (1)
    {
        cout << "Please Enter# ";
        getline(cin, inbuffer);
        if (inbuffer == "quit")
            break;

        ssize_t n = write(sockfd, inbuffer.c_str(), inbuffer.size());
        if (n > 0)
        {
            char buffer[1024];
            ssize_t m = read(sockfd, buffer, sizeof(buffer) - 1);
            if (m > 0)
            {
                buffer[m] = 0;
                cout << "get a echo message ->" << buffer << endl;
            }
            else if (m == 0)
            {
                // 通信结束
                break;
            }
            else
            {
                ret = false;
            }
        }
        else
        {
            ret = false;
        }
    }
END:
    close(sockfd);
    return ret;
}

// ./tcp_client serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return Usage_Err;
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    int cnt = 1;
    while (cnt <= Retry_Count)
    {
        bool result = visitServer(serverip, serverport, &cnt);
        if (result)
            break;
        else
        {
            sleep(1);
            cout << "Server offline, retrying..., count : " << cnt << endl;
            cnt++;
        }
    }

    if (cnt >= Retry_Count)
    {
        cout << "server offline" << endl;
    }
    return 0;
}